<?php
namespace Api\Controller;
use Think\Controller;
class CommonController extends Controller\RestController {

    protected $accountDetailModel;
    protected $collectModel;
    protected $commentModel;
    protected $drawbackModel;
    protected $masterApplyModel;
    protected $orderModel;
    protected $payModel;
    protected $regionModel;
    protected $regionRelationshipModel;
    protected $timeManagerModel;
    protected $userModel;
    protected $wechatMenuModel;
    protected $wechatMenuItemModel;
    protected $withdrawModel;
    protected $bannerModel;
    protected $levelModel;
    protected $masterLevelModel;
    protected $mobileCodeModel;

    protected $currentModel;

    protected $returnData;

    protected $geohash;

        public function _initialize() {

            header("Access-Control-Allow-Origin:*");
            header('Access-Control-Allow-Headers: X-Requested-With,SIGN');
            
//            if($this->_method !== 'post') {
//                $this->mflag=false;
//                $data['errorCode']=C('ERROR_CODE.ERROR_METHOD');
//                $data['errorMsg']=C('ERROR_MSG.ERROR_METHOD');
//                $this->response($data,'json');
//                exit();
//            }

            import('@.Util.geohash');

            $this->geohash = new \Geohash();

            $this->returnData['errorCode'] = 200;
            $this->returnData['errorMsg'] = '';

            $this->accountDetailModel = D("AccountDetail");
            $this->collectModel = D("Collect");
            $this->commentModel = D("Comment");
            $this->drawbackModel = D("Drawback");
            $this->masterApplyModel = D("MasterApply");
            $this->orderModel = D("Order");
            $this->payModel = D("Pay");
            $this->regionModel = D("Region");
            $this->regionRelationshipModel = D("RegionRelationship");
            $this->timeManagerModel = D("TimeManager");
            $this->userModel = D("User");
            $this->wechatMenuModel = D("WechatMenu");
            $this->wechatMenuItemModel = D("WechatMenuItem");
            $this->withdrawModel = D("Withdraw");
            $this->bannerModel = D("Banner");
            $this->levelModel = D("Level");
            $this->masterLevelModel = D("MasterLevel");
            $this->mobileCodeModel = D("MobileCode");

        }  

        public function vcodeImage() {
            
            $config =    array(
                'length'      =>    4,     // 验证码位数
                'useNoise'    =>    false, // 关闭验证码杂点
            );
            
            $Verify = new \Think\Verify($config);
            
            $Verify->entry();
        }
        
        function checkVerify($code, $id = ''){
            $verify = new \Think\Verify();
            return $verify->check($code, $id);
        }
        
        function errorReturn($errorEnum) {
            $this->returnData['errorCode'] = C('ERROR_CODE.'.$errorEnum);
            $this->returnData['errorMsg'] = C('ERROR_MSG.'.$errorEnum);
            $this->response($this->returnData, 'json');
            exit();
        }
        
        public function sendMobileCode() {
            
            $mobile = I('post.mobile');
            
            $num = rand(1000,9999);
            
            mms(C('mmskey'), $mobile, "验证码为：".$num."请在10分钟之内输入");
            
            $map['mobile'] = $mobile;
            
            $mobileCode = $this->mobileCodeModel->where($map)->find();
            
            if(isNullOrEmpty($mobileCode)) {
                
                $data['mobile'] = $mobile;
                $data['code'] = $num;
                $data['create_time'] = getCurrentDate();
                
                $this->mobileCodeModel->add($data);
                
            } else {
                
                $mobileCode['code'] = $num;
                $mobileCode['create_time'] = getCurrentDate();
                
                $this->mobileCodeModel->where($map)->save($mobileCode);
                
            }
            
            $this->response($this->returnData, 'json');
            
        }

        public function checkMobileCode($mobile, $code) {

            $mobileCodeMap['mobile'] = $mobile;
            $mobileCode = $this->mobileCodeModel->where($mobileCodeMap)->find();

            //验证短信验证码是否一致
            if(isNullOrEmpty($mobileCode) || $code != $mobileCode['code']) {

                return false;

            }

            //删除手机验证码记录
            $this->mobileCodeModel->where($mobileCodeMap)->delete();

            return true;

        }

        public function uploadImage() {

            $xmlstr = $GLOBALS['HTTP_RAW_POST_DATA'];
            if (empty($xmlstr))
                $xmlstr = file_get_contents('php://input');

            $arr = explode('&', $xmlstr);

            $fileStreamStr = $arr[1];

            $fileStreamArr = explode('=', $fileStreamStr);

            $rawStr = rawurldecode($fileStreamArr[1]);

            $rawArr = explode(',', $rawStr);

            $fileStream = base64_decode($rawArr[1]);

            $targetFolder = '/backend/Uploads/files/'; // Relative to the root

            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

            $filename = md5(time()) . '.jpg';//要生成的图片名字

            $image = $fileStream;//得到post过来的二进制原始数据
            $file = fopen($targetPath . $filename, "w");//打开文件准备写入
            fwrite($file, $image);//写入
            fclose($file);//关闭

            $photoUrl = C('rooturl') . $targetFolder . $filename;

            $this->returnData['data']['photoUrl'] = $photoUrl;

            echo json_encode($this->returnData);

        }

        public function uploadImage2() {

            $xmlstr =  $GLOBALS['HTTP_RAW_POST_DATA'];
            if(empty($xmlstr))
                $xmlstr = file_get_contents('php://input');

            $arr = explode('&', $xmlstr);

            $fileStreamStr = $arr[1];

            $fileStreamArr = explode('=', $fileStreamStr);

            $fileStream = base64_decode(rawurldecode($fileStreamArr[1]));

            $targetFolder = '/Uploads/files'; // Relative to the root

            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;

            $filename = md5(time()) . '.jpg';//要生成的图片名字

            $image = $fileStream;//得到post过来的二进制原始数据
            $file = fopen($targetPath.$filename,"w");//打开文件准备写入
            fwrite($file,$image);//写入
            fclose($file);//关闭

            $photoUrl = C('rooturl') . $targetFolder . $filename;

            $this->returnData['data']['photoUrl'] = $photoUrl;

            echo json_encode($this->returnData);

        }
        
        public function getCurrentTime() {
            return date('Y-m-d H:i:s');
        }
        
        public function calculateSecondGap($from, $to) {
            $min=ceil(strtotime($to)-strtotime($from));
            return $min;
        }
        
        public function calculateMinGap($from, $to) {
            $min=ceil($to-$from)/60;
            return $min;
        }
        
        /** 
        * @desc 根据两点间的经纬度计算距离 
        * @param float $lat 纬度值 
        * @param float $lng 经度值 
        */
        function getDistance($lat1, $lng1, $lat2, $lng2) { 
            
            $earthRadius = 6367000; //approximate radius of earth in meters 

            /* 
            Convert these degrees to radians 
            to work with the formula 
            */

            $lat1 = ($lat1 * pi() ) / 180; 
            $lng1 = ($lng1 * pi() ) / 180; 

            $lat2 = ($lat2 * pi() ) / 180; 
            $lng2 = ($lng2 * pi() ) / 180; 

            /* 
            Using the 
            Haversine formula 

            http://en.wikipedia.org/wiki/Haversine_formula 

            calculate the distance 
            */

            $calcLongitude = $lng2 - $lng1; 
            $calcLatitude = $lat2 - $lat1; 
            $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2); 
            $stepTwo = 2 * asin(min(1, sqrt($stepOne))); 
            $calculatedDistance = $earthRadius * $stepTwo; 

            return round($calculatedDistance);  //这个计算结果单位是M
        } 
  
	public function guid() {
            
            if (function_exists('com_create_guid')) {
                return com_create_guid();
            } else {
                mt_srand((double) microtime() * 10000); //optional for php 4.2.0 and up.
                $charid = strtoupper(md5(uniqid(rand(), true)));
                $hyphen = chr(45); // "-"
                $uuid = //chr(123)// "{"
                        substr($charid, 0, 8) . $hyphen
                        . substr($charid, 8, 4) . $hyphen
                        . substr($charid, 12, 4) . $hyphen
                        . substr($charid, 16, 4) . $hyphen
                        . substr($charid, 20, 12);
                //.chr(125);// "}"
                return $uuid;
            }
    }

    //获取地区
    public function getRegionList() {

        $id = I('post.id');

        $regionMap['pid'] = $id;
        $regionMap['grade'] = 2;
        $regionList = $this->regionModel
                ->field("name")
                ->where($regionMap)
                ->order("regionId asc")
                ->select();

        echo json_encode($regionList);

    }

    //获取星座
    public function getConstellation() {

        $birthday = I('post.birthday');
        $format = I('post.format');

        @header('Content-type: text/html;charset=UTF-8');

        $pattern = '/^\d{4}-\d{1,2}-\d{1,2}$/';

        if (!preg_match($pattern, $birthday, $matchs)) {
            return null;
        }

        $date = explode('-', $birthday);
        $year = $date[0];
        $month = $date[1];
        $day   = $date[2];

        if ($month <1 || $month>12 || $day < 1 || $day >31) {
            return null;
        }

        //设定星座数组
        $constellations = array(
            '摩羯座', '水瓶座', '双鱼座', '白羊座', '金牛座', '双子座',
            '巨蟹座','狮子座', '处女座', '天秤座', '天蝎座', '射手座',);

        //设定星座结束日期的数组，用于判断
        $enddays = array(19, 18, 20, 20, 20, 21, 22, 22, 22, 22, 21, 21,);

        //如果参数format被设置，则返回值采用format提供的数组，否则使用默认的数组
        if ($format != null) {
            $values = $format;
        }

        else {
            $values = $constellations;
        }

        //根据月份和日期判断星座
        switch ($month) {
            case 1:
                if ($day <= $enddays[0]) {
                    $constellation = $values[0];
                }
                else {
                    $constellation = $values[1];
                }
                break;
            case 2:
                if ($day <= $enddays[1]) {
                    $constellation = $values[1];
                }
                else {
                    $constellation = $values[2];
                }
                break;
            case 3:
                if ($day <= $enddays[2]) {
                    $constellation = $values[2];
                }
                else {
                    $constellation = $values[3];
                }
                break;
            case 4:
                if ($day <= $enddays[3]) {
                    $constellation = $values[3];
                }
                else {
                    $constellation = $values[4];
                }
                break;
            case 5:
                if ($day <= $enddays[4]) {
                    $constellation = $values[4];
                }
                else {
                    $constellation = $values[5];
                }
                break;
            case 6:
                if ($day <= $enddays[5]) {
                    $constellation = $values[5];
                }
                else {
                    $constellation = $values[6];
                }
                break;
            case 7:
                if ($day <= $enddays[6]) {
                    $constellation = $values[6];
                }
                else {
                    $constellation = $values[7];
                }
                break;
            case 8:
                if ($day <= $enddays[7]) {
                    $constellation = $values[7];
                }
                else {
                    $constellation = $values[8];
                }
                break;
            case 9:
                if ($day <= $enddays[8]) {
                    $constellation = $values[8];
                }
                else {
                    $constellation = $values[9];
                }
                break;
            case 10:
                if ($day <= $enddays[9]) {
                    $constellation = $values[9];
                }
                else {
                    $constellation = $values[10];
                }
                break;
            case 11:
                if ($day <= $enddays[10]) {
                    $constellation = $values[10];
                }
                else {
                    $constellation = $values[11];
                }
                break;
            case 12:
                if ($day <= $enddays[11]) {
                    $constellation = $values[11];
                }
                else {
                    $constellation = $values[0];
                }
                break;
        }

        echo json_encode($constellation);
    }


}